<template>
  <el-drawer title="建议内容" size="1000px" :with-header="false" :visible.sync="drawer">
    <div class="advice-box">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-position="left" label-width="80px">
        <div class="advice-add">
          <div class="advice-title" v-if="messageType === 'add'">新增稽核标准</div>
          <div class="advice-title" v-else>编辑稽核标准</div>
          <el-form-item label="标准名称" prop="checkName">
            <el-input placeholder="请输入标准名称" maxlength="50" v-model="form.checkName"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input placeholder="请输入备注" maxlength="50" v-model="form.remark"></el-input>
          </el-form-item>
        </div>
        <div>
          <div class="advice-title">新增明细</div>
          <div v-for="(item, index) in form.checkModuleVoList" :key="index">
            <div class="audit-box">
              <div class="audit-detail form-box">
                <el-form-item
                  label-width="80px"
                  :label="`模块${index+1}`"
                  :prop="`checkModuleVoList[${index}][moduleName]`"
                  :rules="[{required: true,message:'请输入模块名称',trigger: 'change'}]">
                  <el-input placeholder="请输入模块名称" maxlength="50" v-model="item.moduleName"></el-input>
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item
                      label-width="80px"
                      label="分值"
                      :prop="`checkModuleVoList[${index}][score]`"
                      :rules="[{ required: true, validator: (rule, value, callback) => validatorModuleScore(rule, value, callback, index), trigger: 'change' }]"
                    >
                      <el-input placeholder="请输入分值" v-model="item.score"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="可否加分" :prop="`checkModuleVoList[${index}][isAllowAddScore]`">
                      <el-select v-model="item.isAllowAddScore" placeholder="请选择">
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="稽核附件" :prop="`checkModuleVoList[${index}][isAllowAttach]`">
                      <el-select v-model="item.isAllowAttach" placeholder="请选择">
                        <el-option label="必填" :value="1"></el-option>
                        <el-option label="非必填" :value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <div class="audit-sub-item">
                  <div v-for="(subItem, subIndex) in item.checkCriteriaVoList" :key="subIndex" class="audit-sub-box">
                    <div class="form-box">
                      <el-row :gutter="10">
                        <el-col :span="12">
                          <el-form-item
                            label-width="80px"
                            :label="`指标${subIndex+1}`"
                            :prop="`checkModuleVoList[${index}][checkCriteriaVoList][${subIndex}][criteriaName]`"
                            :rules="[{ required: true, message:'请输入稽核指标', trigger: 'change' }]"
                          >
                            <el-input placeholder="请输入稽核指标" maxlength="50" v-model="subItem.criteriaName"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item
                            label-width="50px"
                            label="分值"
                            :prop="`checkModuleVoList[${index}][checkCriteriaVoList][${subIndex}][score]`"
                            :rules="[{ required: false, validator: (rule, value, callback) => validatorCriterScore(rule, value, callback, index,subIndex), trigger: 'change' }]">
                            <el-input placeholder="不设置分项分值"  v-model="subItem.score"></el-input>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <div v-for="(endItem, endIndex) in subItem.checkStandardVoList" :key="endIndex">
                        <el-row :gutter="10">
                          <el-col :span="12">
                            <el-form-item
                              label-width="80px"
                              :label="`标准${endIndex+1}`"
                              :prop="`checkModuleVoList[${index}][checkCriteriaVoList][${subIndex}][checkStandardVoList][${endIndex}][standardName]`"
                              :rules="[{ required: true, message:'请输入作业标准', trigger: 'change' }]"
                            >
                              <el-input placeholder="请输入作业标准" maxlength="50" v-model="endItem.standardName"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="8">
                            <el-form-item
                              label-width="50px"
                              label="分值"
                              :prop="`checkModuleVoList[${index}][checkCriteriaVoList][${subIndex}][checkStandardVoList][${endIndex}][score]`"
                              :rules="[{ required: false, validator: (rule, value, callback) => validatorStandardScore(rule, value, callback, index), trigger: 'change' }]">
                              <el-input placeholder="不设置分项分值" v-model="endItem.score"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="4">
                            <div class="audit-icon">
                              <i style="cursor: pointer;" class="el-icon-circle-plus-outline" @click="addGrandSonChild(endIndex, subItem.checkStandardVoList)"></i>
                              <i style="cursor: pointer;" class="el-icon-remove-outline" @click="removeItem(endIndex, subItem.checkStandardVoList, 3)"></i>
                            </div>
                          </el-col>
                        </el-row>
                        <div style="margin-left: 80px; margin-right: 10px; margin-bottom: 20px;">
                          <el-row>
                            <el-col :span="20"><el-input v-model="endItem.deductionItem" maxlength="50" placeholder="请输入扣分标准" /></el-col>
                          </el-row>
                        </div>
                      </div>
                    </div>
                    <div class="audit-icon">
                      <i style="cursor: pointer;" class="el-icon-circle-plus-outline" @click="addSonChild(subIndex, item.checkCriteriaVoList)"></i>
                      <i style="cursor: pointer;" class="el-icon-remove-outline" @click="removeItem(subIndex, item.checkCriteriaVoList, 2)"></i>
                    </div>
                  </div>
                </div>
              </div>
              <div class="audit-icon">
                <i style="cursor: pointer;" class="el-icon-circle-plus-outline" @click="addSelf(index, form.checkModuleVoList)"></i>
                <i style="cursor: pointer;" class="el-icon-remove-outline" @click="removeItem(index, form.checkModuleVoList, 1)"></i>
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <div class="advice-submit">
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import _ from 'lodash'
import { numberValid, isNumberOne } from '@/utils/validate'
import { addAuditTable, checkAuditTable } from '@/api/auditManagement/audit'
import { editAuditTable } from '../../../api/auditManagement/audit'
export default {
  data() {
    return {
      drawer: false,
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      projectList: [],
      messageData: {},
      historyMessage: [],
      form: {},
      messageType: 'add',
      rules: {
        checkName: [
          { required: true, message: '请输入标准名称', trigger: 'change' },
        ],
      }
    }
  },
  methods: {
    init(id){
      this.drawer = true
      this.$nextTick(() => {
        if(this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate()
        }
      })
      if(id) {
        this.messageType = 'edit'
        checkAuditTable(id).then(res => {
          this.form = res
        })
      } else {
        this.form = this.initForm()
        this.messageType = 'add'
      }
    },
    cancel() {
      this.drawer = false
    },
    grandSonForm(){
      return {
        checkStandardId: '',
        deductionItem: '',
        sortNum: 1,
        score: '',
        standardName: ''
      }
    },
    sonForm(){
      return {
        checkCriteriaId: '',
        criteriaName: '',
        sortNum: 1,
        score: '',
        checkStandardVoList: [this.grandSonForm()]
      }
    },
    selfForm(){
      return {
        moduleName: '',
        checkModuleId: '',
        isAllowAddScore: 1,
        isAllowAttach: 1,
        sortNum: 1,
        score: '',
        checkCriteriaVoList: [this.sonForm()]
      }
    },
    initForm(){
      return {
        checkTableId: '',
        checkName: '',
        remark: '',
        checkModuleVoList: [this.selfForm()]
      }
    },
    addSelf(index, voList) {
      if(voList.length < 100) {
        voList.push(this.selfForm())
      }
    },
    addSonChild(subIndex, voList) {
      if(voList.length < 100) {
        voList.push(this.sonForm())
      }
    },
    addGrandSonChild(endIndex, voList) {
      if(voList.length < 100) {
        voList.push(this.grandSonForm())
      }
    },
    removeItem(index, voList, type){
      if((type === 1 || type === 2 || type === 3) && voList.length === 1) {
        return
      }
      voList.splice(index, 1)
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let selfNum = 1
          let sonNum = 1
          let grandSonNum = 1
          this.form.checkModuleVoList.forEach(item => {
            item.sortNum = selfNum
            selfNum += 1
            item.checkCriteriaVoList.forEach(cItem => {
              cItem.sortNum = sonNum
              sonNum += 1
              cItem.checkStandardVoList.forEach(sItem => {
                sItem.sortNum = grandSonNum
                grandSonNum += 1
              })
            })
          })
          if(this.messageType === 'add'){
            addAuditTable(this.form).then(res => {
              this.drawer = false
              this.$emit('update')
            })
          } else {
            editAuditTable(this.form).then(res => {
              this.drawer = false
              this.$emit('update')
            })
          }
        }
      })
    },
    validatorModuleScore(rule, value, callback, index){
      if(!value && value !== 0) {
        callback(new Error('请输入分值'));
      }
      if(!numberValid(value)) {
        callback(new Error('分值只能是0-100的整数'));
      }
      let moduleItem = this.form.checkModuleVoList[index]
      let criterScore = this.totalScore(moduleItem.checkCriteriaVoList)
      if(parseInt(moduleItem.score) < criterScore) {
        callback(new Error(`模块的分值必须大于指标的分值总和`));
      }
      let standardScore = this.totalStandardScore(moduleItem.checkCriteriaVoList)
      if(parseInt(moduleItem.score) < standardScore) {
        callback(new Error(`模块的分值必须大于标准的分值总和`));
      }
      callback()
    },
    validatorCriterScore(rule, value, callback, index, subIndex){
      if(!value) {
        callback();
      } else if(!isNumberOne(value) || value < 0 || value > 100) {
        callback(new Error('分值只能是0-100的数值并且只能保留一位小数'));
      }
      let moduleItem = this.form.checkModuleVoList[index]

      callback()
    },
    validatorStandardScore(rule, value, callback, index){
      if(!value) {
        callback();
      } else if(!isNumberOne(value) || value < 0 || value > 100) {
        callback(new Error('分值只能是0-100的数值并且只能保留一位小数'));
      }
      callback()
    },
    totalScore(list){
      // 分值求和
      let score = 0
      if(list && list.length > 0) {
        list.forEach(item => {
          if(item.score != null && item.score != ''){
            score += parseInt(item.score)
          }
        })
      }
      return score
    },
    totalCriterScore(list){
       // 分值求和
       let score = 0
      if(list && list.length > 0) {

      }
      return score
    },
    totalStandardScore(list){
      // 分值求和
      let score = 0
      if(list && list.length > 0) {
        list.forEach(item => {
          if(item.checkStandardVoList && item.checkStandardVoList.length > 0){
            item.checkStandardVoList.forEach(item2 => {
              score += parseInt(item2.score)
            })
          }
        })
      }
      return score
    }
  }
}
</script>
<style scoped lang="scss">
.advice-box{
  position: relative;
  padding: 20px;
  height: 100%;
  overflow: auto;
  .form-box{
    border: 1px solid #999999;
    padding: 10px;
    border-radius: 5px;
  }
  .advice-title{
    font-weight: bold;
    font-size: 18px;
    margin: 20px 0 15px 0;
  }
  .audit-box{
    display: flex;
    flex-direction: row;
  }
  .audit-detail{
    flex: 1;
    background: #f2f2f2;
    color: #000000;
    margin-bottom: 20px;
  }
  .audit-sub-item{
    margin-left: 60px;
  }
  ::v-deep .el-form-item__error{
    width: 260px;
  }
  .audit-sub-box{
    display: flex;
    flex-direction: row;
    margin-bottom: 20px;
  }
  .audit-icon{
    width: 100px;
    text-align: center;
    font-size: 30px;
    color: #00afff;
  }
  .advice-submit{
    margin: 20px 0;
    text-align: center;
  }
}
</style>
